<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警示消息alert -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        :closable="false"
        show-icon
        type="warning">
      </el-alert>
      <!-- 选择商品分类 级联选择器 -->
      <div style="margin:10px 0">
        选择商品分类:
        <el-cascader
          v-model="selectOpt"
          :options="goodsCateList"
          :props="propsObj"
          @change="handleChange">
        </el-cascader>
      </div>
      <!-- tabs标签页  切换栏 -->
      <el-tabs v-model="tabsActiveName" @tab-click="tabsHandleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isDisable" @click="addParams">添加参数</el-button>
          <el-table :data="manyTableParams" border >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable @close="delAttr(scope.row,i)"  v-for="(item,i) in scope.row.attr_vals" :key="i" style="margin:7px">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <!-- 方便获取整行数据 -->
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParams(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only" >
          <el-button type="primary" size="mini" :disabled="isDisable"  @click="addParams">添加属性</el-button>
           <el-table :data="onlyTableParams" border >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable @close="delAttr(scope.row,i)"  v-for="(item,i) in scope.row.attr_vals" :key="i" style="margin:7px">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <!-- 方便获取整行数据 -->
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParams(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      :title="tabsActiveName=='many'?'添加动态参数':'添加静态属性'"
      :visible.sync="AddDialogVisible"
      @close="AddDialogVisibleClose"
      width="40%">
      <el-form :model="addRuleForm" :rules="addRuleFormRules" ref="addRuleFormRef" label-width="100px" >
        <el-form-item :label="tabsActiveName=='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="addRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subAddParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog
      :title="tabsActiveName=='many'?'修改动态参数':'修改静态属性'"
      :visible.sync="editDialogVisible"
      @close="editDialogVisibleClose"
      width="40%">
      <el-form :model="editRuleForm" :rules="editRuleFormRules" ref="editRuleFormRef" label-width="100px" >
        <el-form-item :label="tabsActiveName=='many'?'动态参数':'静态属性'" prop="attr_name">
          <el-input v-model="editRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {

  data () {
    return {
      goodsCateList:[],
      selectOpt:[1,3,6],// 选取之后的数据  分类id  1,3,6设置默认值
      propsObj:{ 
        expandTrigger: 'hover',
        label:'cat_name', // 分类名称
        value:'cat_id'  // 分类id
       },
      tabsActiveName:'many', // 当前选中项 区别选中的是静态参数还是动态属性
      onlyTableParams:[],  // 静态参数
      manyTableParams:[],   // 动态属性
      AddDialogVisible:false,  // 添加分类对话框  
      addRuleForm:{    // 添加静态参数.动态属性数据  
        attr_name:''
      },
      addRuleFormRules:{
        attr_name:[
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      editDialogVisible:false,// 编辑分类对话框
      editRuleForm:{
        attr_name:''
      },
      editRuleFormRules:{
        attr_name:[
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      RowAttr_id:0, // 编辑分类时获取的参数属性id 方便别的方法获取
      // 添加参数属性标签
      // inputVisible:false,   // 不可行  这样是 是一个数据绑定多行  需要一行绑定一个数据 
      // inputValue:''

    }
  },

  methods: {
    // 获取分类数据
    async getGoodsCate() {
      // 获取分类数据
      const {data:res} = await this.$http.get('categories')
      // console.log(res)
      if(res.meta.status == 200) {
        this.goodsCateList = res.data
      }
      // console.log(this.goodsCateList)
    },
    
    // 选择商品分类和tabs切换都要发请求获取最新参数数据 解决tabs栏切换参数数据不能实时改变 封装函数
    async getParams() {
      // console.log(this.selectOpt)
      if(this.selectOpt.length != 3) {// 选择一级 二级  级联选择和表格数据清空
        this.selectOpt = []
        this.onlyTableParams = []
        this.manyTableParams = []
      }
      // console.log(this.selectOpt)
      // console.log(this.catId) 三级的id
      var {data:res} =  await this.$http.get(`categories/${this.catId}/attributes`,{
        params:{sel:this.tabsActiveName} // 如果接口文档get请求 不是携带url中 那就是body中  通过params来传递
      })
      // console.log(res)
      // 获取展开行的数据
      res.data.forEach(item => {
        // item.attr_vals = item.attr_vals.split(' ') //  将数据转化为数组
        item.attr_vals =  item.attr_vals.length == 0? []:item.attr_vals.split(' ')
        item.inputVisible = false  // 给每一行添加属性
        item.inputValue = ''
      })
      console.log(res.data)
      // 
      if(res.meta.status == 200) {
        this.$message.success('获取成功')
        // console.log(res.data)
        // 将响应的数据存到data中 通过tabsActiveName来判断动态参数  还是静态属性
        if(this.tabsActiveName == 'only') {
          this.onlyTableParams = res.data
          // console.log(this.onlyTableParams)
        } else {
          this.manyTableParams = res.data
          // console.log(this.manyTableParams)
        }
      }
    },
    // 选择商品分类时
    async handleChange() {
      this.getParams()
    }, 

    // tabs 切换栏 切换时触发
    tabsHandleClick() { 
      // console.log(this.tabsActiveName)
      this.getParams()
      
    },
    // 添加参数对话框
    addParams() {
      this.AddDialogVisible = true
    },
    // 关闭添加参数对话框
    AddDialogVisibleClose() {
      // 关闭对话框重置表单
      this.$refs.addRuleFormRef.resetFields()
    },
    // 点击确定添加参数
    subAddParams() {
      // 发送请求前进行预校验
      this.$refs.addRuleFormRef.validate(async flag => {
        if(!flag) return 
        var {data:res} = await this.$http.post(`categories/${this.catId}/attributes`,{
          attr_name:this.addRuleForm.attr_name,
          attr_sel:this.tabsActiveName
        }) 
        console.log(res)
        if(res.meta.status == 201) {
          this.$message.success('添加成功')
          this.AddDialogVisible = false
          this.getParams()
        }
      })
    },
    // 关闭编辑对话框
    editDialogVisibleClose() {
      // 关闭对话框重置表单
      this.$refs.editRuleFormRef.resetFields()
    },
    // 点击确定修改参数
    subEditParams() {
      // 预校验
      this.$refs.editRuleFormRef.validate( async flag => {
        if(!flag) return 
        // console.log(this.RowAttr_id)// 属性id
        var {data:res} = await this.$http.put(`categories/${this.catId}/attributes/${this.RowAttr_id}`,{
          attr_name:this.editRuleForm.attr_name,
          attr_sel:this.tabsActiveName
        })
        if(res.meta.status == 200) {
          this.$message.success('修改成功')
          this.editDialogVisible = false
          this.getParams()
        }
      })
      
    },
    // 编辑参数对话框
    editParams(row) {
      // console.log(row)
      // subEditParams函数中需要拿到属性id  就需要把该函数的属性id保存到data中  让他可以获取到
      this.RowAttr_id = row.attr_id
      this.editRuleForm.attr_name = row.attr_name
      this.editDialogVisible = true
    },
    // 删除分类参数
    async delParams(row) {
      // 删除之前用弹框与用户交互
      var result = await this.$confirm('确认要删除该属性吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(result)
      if(result == 'confirm') {
        this.$http.delete(`categories/${this.catId}/attributes/${row.attr_id}`)
        this.getParams()
      }
    },
    // 添加参数标签
    // 按下回车键或失去焦点触发
    async handleInputConfirm(row) {
      // 判断用户输入的是否有空格或没输入内容
      if(row.inputValue.trim().length == 0) {
        row.inputValue = '' // 清空内容
        row.inputVisible = false  // 隐藏输入框
        return
      }
      // 如果写了内容做后续操作 用户输入的可选项添加到数组中
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      
      // 添加删除可选项共用一个接口
      this.showAttr(row)  // 把row传过去
    },
    showInput(row) {
      // console.log(row)
      row.inputVisible=true
      // 点击自动获取焦点$nextTick是等数据与页面同步之后触发
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async showAttr(row) {
      // 发请求修改后台数据
      const {data:res} = await this.$http.put(`categories/${this.catId}/attributes/${row.attr_id}`,{
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(' ')  // 数组转换字符串  再发送给后台
      })
      console.log(res)
      if(res.meta.status == 200) {
        return this.$message.success('修改成功')
      }
    },
    // 删除可选项 close事件
    delAttr(row,i) {
      // console.log(row)
      // console.log(i)
      row.attr_vals.splice(i,1)
       // 添加删除可选项共用一个接口
      this.showAttr(row)
    }
    
  },
    // 计算属性 单独写 不能写在methods中
  computed:{
    // 没选中第三级 禁用按钮
    isDisable() {
      if(this.selectOpt.length !== 3) return true
        return false
    },
    // 获取三级的id
    catId() {
      if(this.selectOpt.length == 3) return this.selectOpt[2]
        return null
    }
  },

  created () {
    this.getGoodsCate()
    this.getParams() // 页面一加载自动获取参数
  }
}
</script>

<style lang='css' scoped>
  .input-new-tag {
    width: 150px;
  }
</style>
